<template>
  <div>
    <el-dialog v-model="showDialog" :title="`${id ? '编辑' : '新增'}积分`" width="600px" :before-close="cancel">
      <el-form ref="ruleFormRef" v-loading="loading" :model="ruleForm" :rules="rules" label-width="120px"
        class="demo-ruleForm" status-icon>
        <el-form-item label="积分类型" prop="isExternal">
          <el-radio-group v-model="ruleForm.isExternal">
            <el-radio :label="0">
              内部积分
            </el-radio>
            <el-radio :label="1">
              外部积分
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="积分名称" prop="name">
          <el-input v-model="ruleForm.name" maxlength="4" show-word-limit clearable :placeholder="`请填写积分名称`" />
        </el-form-item>


        <el-form-item :label="`兑换比例`" prop="exchangeRatio">

          <el-input v-model.number="ruleForm.exchangeRatio" :min="1" :max="99999999" controls-position="right"
            :placeholder="`请填写兑换比例`"><template #append>积分=1元</template></el-input>
        </el-form-item>
        <template v-if="ruleForm.isExternal === 0">
          <el-form-item :label="`失效时间`" prop="expireType">
            <el-radio-group v-model="ruleForm.expireType">
              <el-radio v-for="item in radioList" :key="item.id" :label="item.id">
                {{
                  item.name
                }}
              </el-radio>
            </el-radio-group>
          </el-form-item>


          <div v-if="ruleForm.expireType == 'relatively'" class="relatively">
            <el-form-item :label="`相对时间`" prop="relatively">
              <el-input-number v-model="ruleForm.relatively" :min="1" controls-position="right" placeholder="请输入周期时间" />
            </el-form-item>
            <el-form-item label-width="20px">
              <el-select v-model="dataForm.timeType">
                <el-option v-for="item in timeList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </div>

          <el-form-item v-if="ruleForm.expireType == 'fixed'" :label="`固定时间`" prop="fixed">
            <el-date-picker v-model="ruleForm.fixed" type="datetime" placeholder="请选择固定时间" />
          </el-form-item>
        </template>

        <template v-if="ruleForm.isExternal === 1">
          <el-form-item label="积分平台" prop="configId">
            <ScSelector v-model="ruleForm.configId" type="config" :params="{ attach: 'currency' }"
              :show-filter-tags="false">
              <template #expand-pop="{ data }">
                {{ data?.title }}
              </template>
            </ScSelector>
          </el-form-item>
        </template>

        <!-- <el-form-item v-if="adminType == 0" :label="`应用机构`" prop="availableInsIds" required>
        <el-tree-select v-model="ruleForm.availableInsIds" :data="departmentData" :props="propsDefault" />
    </el-form-item> -->

        <el-form-item label="积分图标" prop="logo" required>
          <Upload v-model="ruleForm.logo" :limit="1" :show-file-list="false" @success="success">
            <template #default>
              <img v-if="ruleForm.logo" :src="ruleForm.logo" class="avatar">
              <div v-if="!ruleForm.logo" class="upload-box">
                <el-icon class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </div>
              <span v-if="ruleForm.logo" class="el-upload-list__item-actions" @click.stop="">
                <span class="el-upload-list__item-delete" @click.stop="handleRemove()">
                  <el-icon>
                    <Delete />
                  </el-icon>
                </span>
              </span>
            </template>
          </Upload>
        </el-form-item>

        <el-form-item :label="`积分状态`" prop="status">
          <el-switch v-model="ruleForm.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="积分规则">
          <!--          rich-editor: {{form.initialContent}}-->
          <rich-editor ref="richEditorRef" :initial-value="initialValue" @change="handleEditorChange" />
        </el-form-item>
      </el-form>

      <!-- <el-tree-select
    v-model="value"
    :props="{label: 'name'}"
    :data="departmentData"
    multiple
    :render-after-expand="false"
    show-checkbox
  /> -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="formValidate(ruleFormRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import marketingCenterApi from "@/api/marketingCenterApi";
import Upload from "@/components/upload.vue";
import { queryTree } from "@/api/orgManage";
import { QuillEditor } from "@vueup/vue-quill";
import RichEditor from "@/components/RichEditor.vue";
import "@vueup/vue-quill/dist/vue-quill.snow.css";
import type { FormInstance, FormRules } from "element-plus";
const props = defineProps({
  showDialog: Boolean,
  id: Number,
});
const { id, showDialog } = toRefs(props);
const Store = useStore();
const propsDefault = ref({
  label: "name",
  value: "id",
  children: "children",
});
const initialValue = ref("")
const richEditorRef = ref()
const loading = ref(false);
const adminType = Store.state.user.adminType;
const ruleFormRef = ref<FormInstance>();
const departmentData = ref([]);
const radioList = ref([
  { id: "fixed", name: "固定时间" },
  { id: "relatively", name: "相对时间" },
  { id: "dayEnd", name: "当天失效" },
  { id: "weekEnd", name: "周末失效" },
  { id: "monthEnd", name: "月末失效" },
  { id: "yearEnd", name: "年末失效" },
]);
const timeList = ref([
  // {id: '1', name: '年'},
  // {id: '2', name: '月'},
  // {id: '3', name: '周'},
  { id: "4", name: "天" },
  // {id: '5', name: '小时'},
]);
const dataForm = ref({
  timeType: "4",
  day: 60 * 60 * 24,
});
const ruleForm = ref({
  id: "",
  name: "",
  // availableInsIds: '',
  exchangeRatio: 1, // 积分比例
  expireType: "fixed", //积分类型
  expireTime: "", // 周期时间
  logo: "",
  status: 0,
  fixed: "",
  relatively: 1,
  rules: "",
  isExternal: 0,
  configId: null,
});

watch(showDialog, () => {
  console.log("[ id.value ]", id?.value);
  /* ... */
  if (showDialog.value && id?.value) {
    getCurrencyInfoDetail();
  }
});
const handleEditorChange = ({ innerHTML }: any) => {
  ruleForm.value.rules = innerHTML;
};
const getCurrencyInfoDetail = async () => {
  loading.value = true;
  let rs: any = await marketingCenterApi.getCurrencyInfoDetail({ id: id?.value });
  if (rs.code === 200) {
    ruleForm.value = rs.payload;
    initialValue.value = rs.payload.rules
    // ruleForm.value['availableInsIds'] = rs.payload.insId
    // ruleForm.value['relatively'] = 1
    // ruleForm.value['fixed'] = ''

    if (ruleForm.value.expireType == "relatively") {
      ruleForm.value["relatively"] =
        Number(ruleForm.value.expireTime) / dataForm.value.day;
    } else if (ruleForm.value.expireType == "fixed") {
      ruleForm.value["fixed"] = ruleForm.value.expireTime;
    }
  }
  loading.value = false;
};

// const availableInsIdsCheck = (rule: any, value: any, callback: any) => {
//   // debugger

//   // debugger
//   if (ruleForm.value.availableInsIds) {

//     callback()
//   } else {

//     callback(new Error('请选择部门'))
//   }
// }

const logoCheck = (rule: any, value: any, callback: any) => {
  if (ruleForm.value.logo === "") {
    callback(new Error("请添加logo"));
  } else {
    callback();
  }
};
// const checkRelatively = (rule: any, value: any, callback: any) => {
//   if (dataForm.value.relatively) {
//     ruleFormRef.value?.clearValidate('relatively')
//     callback()
//   } else {
//     callback(new Error('请输入相对时间'))
//   }
// }

// const checkFixed = (rule: any, value: any, callback: any) => {
//   if (dataForm.value.fixed) {
//     ruleFormRef.value?.clearValidate('fixed')
//     callback();
//   } else {
//     callback(new Error('请选择固定时间'))
//   }
// }

const rules = reactive<FormRules>({
  isExternal: [{ required: true, message: "请选择积分类型", trigger: ["change"] }],
  name: [{ required: true, message: "请填写积分名称", trigger: ["blur", "change"] }],
  exchangeRatio: [
    { required: true, message: "请填写兑换比例", trigger: ["blur", "change"] },
  ],
  expireType: [{ required: true, message: "请选择类型", trigger: ["blur", "change"] }],
  relatively: [{ required: true, message: "请输入相对时间", trigger: ["blur"] }],
  fixed: [{ required: true, message: "请选择固定时间", trigger: ["blur"] }],
  logo: [{ validator: logoCheck, trigger: ["blur", "change"] }],

  // availableInsIds: [
  //   { validator: availableInsIdsCheck, trigger: ['blur','change']},
  // ],
  status: [{ required: true, message: "请输设置状态", trigger: ["blur", "change"] }],
  configId: [{
    required: true, validator(rule, value, callback) {
      if (!ruleForm.value.configId) {
        callback("请选择积分平台")
        return
      }

      callback()
    }
  }]
});

const formValidate = (formEl: FormInstance | undefined) => {
  if (!formEl) return;

  formEl.validate((valid) => {
    if (valid) {
      submitForm();
    }
  });
};

const submitForm = async () => {
  let params = JSON.parse(JSON.stringify(ruleForm.value));

  if (params.expireType == "fixed") {
    params.expireTime = new Date(params.fixed).getTime();
  } else if (params.expireType == "relatively") {
    params.expireTime = dataForm.value.day * params.relatively;
  }

  if (id?.value) {
    params["id"] = id.value;
  }
  // params.availableInsIds = [params.availableInsIds]
  let rs: any = await marketingCenterApi.AddCurrency(params);
  // if (rs.code === 200) {
  //
  // }
  //   ruleForm.type = modelData?.value.type
  //   ruleForm.userId = modelData?.value.userId
  //   let rs = await integralApi.updateIntegral(ruleForm)
  if (rs.code === 200) {
    ElMessage({
      type: "success",
      message: `${id?.value ? "编辑" : "新增"}积分成功`,
    });
    confirm();
  }
};

const setTreeData = (children: any) => {
  children.forEach((item: { id: any; children: string | any[] }) => {
    if (item.children.length !== 0) {
      setTreeData(item.children);
    } else {
      item["value"] = item.id;
    }
  });
};

const getDepartmentTree = async () => {
  let rs = await queryTree({ name: "", status: "" });
  // setTreeData( rs.payload)
  if (rs.code === 200) {
    departmentData.value = rs.payload;
    setTreeData(departmentData.value);
  }
};

const handleRemove = () => {
  ruleForm.value.logo = "";
};

const success = (val: any) => {
  if (val.url) {
    ruleFormRef.value?.clearValidate("logo");
  }
  ruleForm.value.logo = val.url;
};
const filterNodeMethod = (value: any, data: any) => data.label.includes(value);
const confirm = () => {
  emit("confirm");
  cancel();
};

const cancel = () => {
  ruleForm.value = {
    id: "",
    name: "",
    // availableInsIds: '',
    exchangeRatio: 1, // 积分比例
    expireType: "fixed", //积分类型
    expireTime: "", // 周期时间
    logo: "",
    status: 0,
    fixed: "",
    relatively: 1,
    rules: "",
  };

  setTimeout(() => {
    ruleFormRef.value?.resetFields();

  }, 0);
  richEditorRef.value.clearEditor(); // 清空富文本数据
  emit("cancel");
};
const emit = defineEmits(["confirm", "cancel"]);

onBeforeMount(() => {
  getDepartmentTree();
});
</script>

<style lang="scss" scoped>
:deep(.el-input-number) {
  width: 100%;
}

.el-form {
  padding-right: 80px;
}

:deep(.avatar) {
  width: 75px;
  height: 75px;
  display: block;
}

:deep(.el-upload) {
  width: 100px;
  height: 100px;
  //   border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

:deep(.el-upload:hover) {
  //   border-color: var(--el-color-primary);
}

.upload-box {
  width: 98px;
  height: 98px;
  line-height: 98px;
  text-align: center;
  display: block;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  position: relative;
  overflow: hidden;
}

.upload-box:hover {
  border-color: var(--el-color-primary);
}

:deep(.el-icon.avatar-uploader-icon) {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}

.el-upload-list__item-actions {
  display: none;
  width: 100%;
  height: 100%;
  background: rgba($color: #000000, $alpha: 0.6);
  position: absolute;
  text-align: center;
  line-height: 100px;

  .el-upload-list__item-delete {
    color: #fff;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-size: 20px;
  }
}

.el-upload:hover .el-upload-list__item-actions,
.el-upload-list__item-delete {
  display: block;
}

:deep(.el-input__inner) {
  text-align: left;
}

.el-select {
  width: 100%;
}

:deep(.el-input--prefix) {
  width: 94%;

  .el-input__wrapper {
    width: 100%;
  }
}

.relatively {
  display: flex;
  flex-wrap: nowrap;
}
</style>
